package com.lute.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.model.Approver;
import com.lute.model.Client;
import com.lute.model.ClientAccountingPeriod;
import com.lute.model.ClientAdmin;
import com.lute.model.Employee;
import com.lute.model.User;
import com.lute.utils.ServerErrorResponse;

@Controller
public class GetAvaliableAccountingPeriodsServlet {
	
	@RequestMapping(value="/getAvailableAccountingPeriods", method= RequestMethod.POST, headers = "Content-type=application/json")
	public @ResponseBody String getAvailableAccountingPeriods(@RequestBody String jsonFromUI,HttpServletRequest request) throws JSONException {
		String result = "";
		JSONObject jsonReq;
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			jsonReq = new JSONObject(jsonFromUI);
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}

		int userId = (Integer)session.getAttribute("sessionUserId");
		String userRole = (String) session.getAttribute("role");
		
		// parameters from JSON object
		int clientId = Integer.parseInt(jsonReq.getString("clientId"));
		System.out.println("/getAvailableAccountingPeriod: " + "clientId: " + clientId + ", Role: " + userRole);
		
		try {
			if (userRole.equals("admin")){
				jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
				result = jsonRes.toString();
				System.out.println("/getAvailableAccountingPeriod: " + "ADMIN logged in. Can not load ClientAccountingPeriod");
				return result;
			} else {
				
				if (userRole.equals("employee")){
					Employee employee = Employee.getEmployeeFromDBWithProfile("id_user", userId);
					Client client = User.getClientWithAccPeriodByIdFromDB("id_client", clientId);
					
					if (client.getId_client() == employee.getEmployeeProfil().getClient().getId_client()){
						List<ClientAccountingPeriod> clientAccPEriodList = client.getClientAccountingPeriods();
						
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
						
						List<JSONObject> availableAccountingPeriods = new ArrayList<JSONObject>();
						for(ClientAccountingPeriod accPeriod: clientAccPEriodList) {
							JSONObject obj = new JSONObject();
							dateFormat.setCalendar(accPeriod.getDate_from());
							obj.put("from", dateFormat.format(accPeriod.getDate_from().getTime()));
							availableAccountingPeriods.add(obj);
						}
						jsonRes.put("availableAccountingPeriods", availableAccountingPeriods);
						jsonRes.put("result","OK");
						result = jsonRes.toString();
					} else {
						jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
						result = jsonRes.toString();
						return result;
					}
				}
				
				if (userRole.equals("approver")){
					Approver approver = Approver.getApproverWithAllFromDB("id_user", userId);
					Client client = User.getClientWithAccPeriodByIdFromDB("id_client", clientId);
					
					if (client.getId_client() == approver.getApproverProfile().getClient().getId_client()){
						List<ClientAccountingPeriod> clientAccPEriodList = client.getClientAccountingPeriods();
						
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
						
						List<JSONObject> availableAccountingPeriods = new ArrayList<JSONObject>();
						for(ClientAccountingPeriod accPeriod: clientAccPEriodList) {
							JSONObject obj = new JSONObject();
							dateFormat.setCalendar(accPeriod.getDate_from());
							obj.put("from", dateFormat.format(accPeriod.getDate_from().getTime()));
							availableAccountingPeriods.add(obj);
						}
						jsonRes.put("availableAccountingPeriods", availableAccountingPeriods);
						jsonRes.put("result","OK");
						result = jsonRes.toString();
					} else {
						jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
						result = jsonRes.toString();
						return result;
					}
				}
				
				if (userRole.equals("clientAdmin")){
					ClientAdmin clientAdmin = ClientAdmin.getClientAdminFromDBWithClients("id_user", userId);
					List<Client> clientList = clientAdmin.getClientAdminProfil().getClients();
					Client client = User.getClientWithAccPeriodByIdFromDB("id_client", clientId);
					
					for (Client clientFromList : clientList) {
						if (client.getId_client() == clientFromList.getId_client()){
							List<ClientAccountingPeriod> clientAccPEriodList = client.getClientAccountingPeriods();
							
							SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
							
							List<JSONObject> availableAccountingPeriods = new ArrayList<JSONObject>();
							for(ClientAccountingPeriod accPeriod: clientAccPEriodList) {
								JSONObject obj = new JSONObject();
								dateFormat.setCalendar(accPeriod.getDate_from());
								obj.put("from", dateFormat.format(accPeriod.getDate_from().getTime()));
								availableAccountingPeriods.add(obj);
							}
							jsonRes.put("availableAccountingPeriods", availableAccountingPeriods);
							jsonRes.put("result","OK");
							result = jsonRes.toString();
							return result;
						} 
					}
					
					jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
					result = jsonRes.toString();
					return result;
				}
			}
		} catch (NullPointerException npe) {
			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
			result = jsonRes.toString();
			return result;
		}
		return result;
	}
}
